package graduation.project.mutant.strategy;

import graduation.project.body.Expression;
import graduation.project.body.Mutants;
import graduation.project.body.OriginExpression;
import graduation.project.exception.NonExpressionException;

import java.util.ArrayList;

/**
 *  if a boolean expression is a term, TOF fault is a bad dream for this case.
 * @author robin
 *
 */
public class TOFMutantsGen implements MutantsGenerator {

	public Mutants generateMutants(String expression, int mutantsNum) {
		
		try{
			OriginExpression originEx = new OriginExpression(expression);
			return generateMutants(originEx, mutantsNum);
		}catch(NonExpressionException e){
			System.out.println("TOFMutantsGen: the expression is invalid.");
			e.printStackTrace();
		}
		return null;
	}

	public Mutants generateMutants(OriginExpression originEx, int num) {
		
		int count = 0;
		Mutants result = new Mutants(originEx.getExpression(), "TOF");
		ArrayList<Expression> mutantSet = new ArrayList<Expression>();
		String idnf = originEx.getIDNF();
		
		StringBuffer exp = new StringBuffer();
		exp.append(idnf);
		int begin = -1;
		int end = 0;
		int termCount = idnf.split("\\+").length;
		
		String deleteTerm;
		for(int i = 0; i < termCount; i++){
			begin = end;
			end = idnf.indexOf("+" ,begin + 1);
			if(end < 0)
				end = idnf.length();
			try {
				deleteTerm = exp.substring(begin, end);
				if(begin == 0 && end == idnf.length()){	
						break;				
				}else if(begin == 0){
					exp.delete(0, end + 1);
					mutantSet.add(new Expression(exp.toString()));
					exp.insert(0, deleteTerm + "+");
				}else{
					exp.delete(begin, end);
					mutantSet.add(new Expression(exp.toString()));
					exp.insert(begin, deleteTerm);
				}			
			} catch (NonExpressionException e) {
				System.out.println("TOFMutantsGen: the expression is invalid.");
				e.printStackTrace();
			}
			
			if(num != -1 && ++count >= num)
				break;
		}
		
		result.setMutants(mutantSet);
		return result;
	}

}
